package com.taoyibao.hongcanting.http;

import android.content.Context;
import android.net.ParseException;
import android.text.TextUtils;

import com.google.gson.JsonParseException;
import com.taoyibao.hongcanting.R;
import com.taoyibao.hongcanting.cache.SpUtils;
import com.taoyibao.hongcanting.constant.NetCode;
import com.taoyibao.hongcanting.dialog.LoadingDialog;
import com.taoyibao.hongcanting.dialog.ProgressCancelListener;
import com.taoyibao.hongcanting.model.CompanyBaseModel;
import com.taoyibao.hongcanting.model.SanFangBaseModel;
import com.taoyibao.hongcanting.ui.login.activity.LoginActivity;
import com.taoyibao.hongcanting.utils.CodeUtils;
import com.taoyibao.hongcanting.utils.LogUtils;
import com.taoyibao.hongcanting.utils.ToastUtils;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import rx.Subscriber;

public abstract class ProgressSubscriber<T> extends Subscriber<T> implements ProgressCancelListener {

    private static final String TAG = ProgressSubscriber.class.getSimpleName();
    private LoadingDialog mLoadingDialog;

    private Context context;
    private String mText;
    protected boolean showDialog = false;

    public ProgressSubscriber(Context context) {
        this(context, false);
    }

    public ProgressSubscriber(Context context, boolean show) {
        this(context, show, "");
    }

    public ProgressSubscriber(Context context, boolean show, String text) {
        this.context = context;
        this.showDialog = show;
        this.mText = text;
        mLoadingDialog = new LoadingDialog(context);
        mLoadingDialog.setProgressCancelListener(this);
    }

    private void showProgressDialog() {
        if (mLoadingDialog != null && showDialog) {
            if (mText != null) {
                mLoadingDialog.setText(mText);
            }
            mLoadingDialog.show();
        }

    }

    public void dismissProgressDialog() {
        if (mLoadingDialog != null && showDialog)
            mLoadingDialog.dismiss();
    }

    /**
     * 订阅开始时调用
     * 显示ProgressDialog
     */
    @Override
    public void onStart() {

        if (showDialog) {
            showProgressDialog();
        }
    }

    /**
     * 完成，隐藏ProgressDialog
     */
    @Override
    public void onCompleted() {
        dismissProgressDialog();
    }

    /**
     * 统一处理code !=200的情况
     *
     * @param t
     */
    @Override
    public void onNext(T t) {
        if (t instanceof CompanyBaseModel) {
            CompanyBaseModel companyBaseModel = (CompanyBaseModel) t;
            //token过期跳转登录页面
            if (companyBaseModel.code == NetCode.HTTP_300 && SpUtils.getLoginStatus()) {
                ToastUtils.showToast(CodeUtils.getIdString(R.string.dialog_tokenExpired));
                LoginActivity.open(context, "");
                //清除本地缓存的状态
                SpUtils.exist();
            } else if (companyBaseModel.code != NetCode.HTTP_200 && companyBaseModel.code != NetCode.HTTP_300) {
                if (!TextUtils.isEmpty(companyBaseModel.msg)) {
                    ToastUtils.showToast(companyBaseModel.msg);
                } else {
                    ToastUtils.showToast(CodeUtils.getIdString(R.string.string_hintOperationFailed));
                }
            }

        } else if (t instanceof SanFangBaseModel) {
            SanFangBaseModel sanFangBaseModel = (SanFangBaseModel) t;
            if (sanFangBaseModel.Code != NetCode.HTTP_200) {
                if (!TextUtils.isEmpty(sanFangBaseModel.Msg)) {
                    ToastUtils.showToast(sanFangBaseModel.Msg);
                } else {
                    ToastUtils.showToast(CodeUtils.getIdString(R.string.string_hintOperationFailed));
                }
            }
        }

    }

    /**
     * 对错误进行统一处理 httpCode !=200 通信没有成功
     * 隐藏ProgressDialog
     *
     * @param e
     */
    @Override
    public void onError(Throwable e) {
        dismissProgressDialog();
        if (e instanceof ConnectException) {
            ToastUtils.showToast("网络中断，请检查您的网络状态");
        } else if (e instanceof SocketTimeoutException) {
            ToastUtils.showToast("网络中断，请检查您的网络状态");
        } else if (e instanceof UnknownHostException) {
            ToastUtils.showToast("网络中断，请检查您的网络状态");
        } else if (e instanceof SocketException) {
            ToastUtils.showToast("网络中断，请检查您的网络状态");
        } else if (e instanceof ApiException) {

            // 需要后台解决的错误
            ApiException apiException = (ApiException) e;
            if (apiException.errorCode == 403) {
                ToastUtils.showToast("权限不足");
            } else {
                ToastUtils.showToast("网络错误");
            }
            LogUtils.dNormal(TAG + ":onError: ", "errorCode== " + apiException.errorCode + "errorMsg== " + apiException.errorMsg);
        } else {
            if (e instanceof JsonParseException || e instanceof JSONException || e instanceof ParseException) {
                LogUtils.dNormal(TAG + ":onError:解析错误 ", e.getMessage());
            } else {
                LogUtils.dNormal(TAG + ":onError: 未知错误", e.getMessage());
            }
        }
    }


    /**
     * 取消ProgressDialog的时候，取消对observable的订阅，同时也取消了http请求
     */
    @Override
    public void onCancelProgress() {
        if (!this.isUnsubscribed()) {
            this.unsubscribe();
        }
    }
}